<template>
    <van-nav-bar class="topFIX" title="评论" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div class="itemOnlyBox">
        <div class="itemBox">
            <div class="headerBox">
                <img class="img" :src="tmp + item.img" alt="" />
                <div class="username">{{ item.username }}</div>
            </div>
            <div class="context">{{ item.context }}</div>
            <div :class="['likeBox', !item.showFlag ? '' : 'border']">
                <div class="left">{{ getDate(item.created_at) }}</div>
                <div class="right">
                    <div v-if="!item.showLoading" :class="['rightItem', item.flag ? 'like' : 'nolike']" @click="like(item)">
                        点赞:{{ item.likeNum ? item.likeNum : 0 }}
                    </div>
                    <div v-else :class="['rightItem', item.flag ? 'like' : 'nolike']">
                        <van-loading type="spinner" size="8px" />
                    </div>
                    <div class="rightItem addCommentNew" @click="addCommentNew">评论{{ item.commentNum }}</div>
                </div>
            </div>
        </div>
        <div v-if="item.commentNum" class="commentBox2">
            <div v-for="i in commentBody.list" :key="i.id">
                <div class="commentModelBoxitemBox">
                    <div>
                        <!-- {{ i.username }}{{ i.parentUserName ? " 回复 " + i.parentUserName : "" }}:{{ i.context }}
                        <span class="timeBox">{{ getDate(i.created_at) }}</span
                        ><span class="smallText" @click="addcomment(i)">点击回复</span> -->
                        <span :class="[i.userId===userInfo.id?'isMe':'']">{{i.username}}</span>
                        <span v-if="i.parentUserName"> > </span>
                        <span v-if="i.parentUserName" :class="[i.parentUserId===userInfo.id?'isMe':'']">{{i.parentUserName}}</span>
                        <span>:</span>
                        {{ i.context }}
                        <span class="timeBox">{{ getDate(i.created_at) }}</span
                        ><span class="smallText" @click="addcomment(i)">点击回复</span>
                    </div>
                </div>
                <!-- <commentModel v-if="i.child" :list="i.child"></commentModel> -->
            </div>
            <div class="more" v-if="commentBody.count > commentBody.list.length" @click="getMore">更多</div>
            <div class="more nomore" v-else>暂无更多</div>
            <!-- <commentModel :list="commentBody.list"></commentModel> -->
        </div>
        <div v-else class="commentBox" @click="show=true">暂无评论，评论一下？</div>
    </div>
    <div class="commentform" v-if="show">
        <van-form @submit="onSubmit">
            <van-field
                v-model="context"
                rows="2"
                autosize
                type="textarea"
                name="context"
                label="评论内容："
                placeholder="请输入评论内容，不超过50字符"
                show-word-limit
                maxlength="50"
                :rules="[{ required: true, message: '请输入评论内容，不超过50字符' }]"
                label-width="70px"
            />
            <div style="margin: 10px" class="buttonbox">
                <van-button size="small" round type="danger" @click="show = false"> 取消 </van-button>
                <van-button size="small" round type="primary" native-type="submit"> 提交 </van-button>
            </div>
        </van-form>
    </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import { commentList2, getList, getlistbyid } from "./api"
import { getDate } from "@/utils/common"
import { instantlist, dataList, createComment } from "./api"
import { showNotify } from "vant"
import {userStore} from "@/store/modules/user"
import { storeToRefs } from "pinia"
import { createlike } from "../main/api"
const userSTate=userStore()
const {userInfo}=storeToRefs(userSTate)
// import commentModel from "./commentModel.vue"
const router = useRouter()
const id = ref<number>()
const item = ref<instantlist>({
    id: undefined,
    userId: undefined,
    title: "",
    context: "",
    img: "",
    likeNum: 0,
    username: "",
    created_at: "",
    commentNum: 0,
    showFlag: false,
    flag: false,
    showLoading: false
})
const context = ref("")
const pageIndex = ref(1)
const pageSize = ref(10)
const commentBody = ref<dataList>({
    list: [],
    count: 0
})
const instantId = ref("")
const show = ref(false)
const tmp = ref(
    import.meta.env.VITE_ENV === "development" ? "http://localhost:9001/static/" : "http://49.232.228.40:9001/static/"
)
onMounted(async () => {
    id.value = JSON.parse(router.currentRoute.value.query.id as string)
    let res = await getlistbyid({ id: id.value as number })
    console.log(res)
    if (res.code === 0) {
        item.value = res.body
    }
    //获取评论详情
    let res1 = await getList({ id: id.value!, pageIndex: pageIndex.value, pageSize: pageSize.value })
    if (res1.code === 0) {
        console.log(res1.body.list)
        commentBody.value.list = InitArr(res1.body.list)
        commentBody.value.count = res1.body.count
        // let arr = res1.body.list
        // InitArr(arr)
        // commentBody.value.list=arr.filter(item=>item.parentId===0)
        // console.log(commentBody.value.list)
    }
})
// const arrList=ref<Array<commentList>>([])
const InitArr = (arr: Array<commentList2>) => {
    for (let i in arr) {
        // console.log(arr[i])
        if (arr[i].parentId != 0) {
            for (let j in arr) {
                if (arr[j].id === arr[i].parentId) {
                    arr[i].parentUserName = arr[j].username
                    arr[i].parentUserId = arr[j].userId
                    // if (!arr[j].child) {
                    //     arr[j].child = []
                    //     arr[i].parentUserName = arr[j].username
                    //     arr[j].child.push(arr[i])
                    // } else {
                    //     arr[i].parentUserName = arr[j].username
                    //     arr[j].child.push(arr[i])
                    // }
                }
            }
        }
    }
    return arr
}
const onClickLeft = () => {
    window.history.go(-1)
}
const getMore = async () => {
    pageIndex.value += 1
    let res = await getList({ id: id.value!, pageIndex: pageIndex.value, pageSize: pageSize.value })
    commentBody.value.list = [...commentBody.value.list, ...InitArr(res.body.list)]
    commentBody.value.count = res.body.count
    item.value.commentNum=res.body.count
}
const parentId=ref(0)
const addcomment = (i:any) => {
    console.log("添加评论",i)
    show.value = !show.value
    console.log(i.id)
    instantId.value = i.instantId
    parentId.value=i.id
}
const onSubmit = async (values: any) => {
    console.log(values)
    console.log("提交")
    console.log({ ...values, instantId: id.value, parentId: instantId.value })
    let res = await createComment({ ...values, instantId: id.value, parentId: parentId.value })
    console.log(res)
    if (res.code === 0) {
        pageIndex.value=1
        show.value = false
        context.value = ""
        showNotify({ type: "primary", message: res.msg })
        let res1 = await getList({ id: id.value!, pageIndex: pageIndex.value, pageSize: pageSize.value })
        commentBody.value.count = res1.body.count
        commentBody.value.list = [...InitArr(res1.body.list)]
        item.value.commentNum=res1.body.count
    } else {
        showNotify({ type: "danger", message: res.msg })
    }
    
}
const addCommentNew=()=>{
    show.value=true
    parentId.value=0
}
const like = async (item: instantlist) => {
    console.log(item.userId)
    console.log(item)
    item.showLoading=true
    let res = await createlike({ instant_id: item.id as number, flag: item.flag ? 1 : 0 })
    if(res.code===0){
        if(item.flag){
            item.flag=false
            item.likeNum!-=1
        }else{
            item.flag=true
            item.likeNum!+=1
        } 
    }
    item.showLoading=false
}
</script>
<style lang="less" scoped>
.topFIX {
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
}
.itemOnlyBox {
    padding: 50px 10px;
    height: 100vh;
    background-color: rgb(248, 247, 247);
    .itemBox {
        background-color: white;
        margin: 5px 0px;
        padding: 10px;
        border-radius: 10px;
        .headerBox {
            display: flex;
            justify-content: flex-start;
            align-items: flex-end;
            margin: 0px 0px 10px 0px;
            .img {
                width: 30px;
                margin-right: 5px;
            }
            .username {
                margin: 0px 0px 0px 0px;
                font-size: 12px;
            }
        }

        .context {
            font-size: 16px;
            margin-bottom: 10px;

            word-wrap: break-word;
        }
        .likeBox {
            font-size: 12px;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            .left {
            }
            .right {
                display: flex;
                justify-content: flex-start;
                .rightItem {
                    margin-left: 5px;
                    
                }   
                .addCommentNew{
                    display: inline-block;
                    background-color: rgba(154, 154, 231,0.5);
                }
                .like {
                    background-color: rgb(248, 76, 76);
                    border-radius: 2px;
                    padding: 0px 2px;
                }
                .nolike {
                    background-color: rgb(189, 188, 188);
                    border-radius: 2px;
                    padding: 0px 2px;
                }
            }
        }
        .border {
            border-bottom: 1px dashed #f1f1f1f1;
        }
        .commentBox {
            padding: 10px 0px;
            font-size: 12px;
            color: #3b3b3bf1;
            transition: 0.3s ease-in;
        }

        .falseBox {
            height: 0px;
            transition: 0.3s ease-in;
            overflow: hidden;
            font-size: 12px;
            color: white;
        }
    }
    .commentBox {
        background-color: rgb(230, 227, 227);
        text-align: center;
        border-radius: 10px;
        padding: 15px;
    }
    .commentBox2 {
        background-color: white;
        border-radius: 10px;
        padding: 15px;
        .commentModelBoxitemBox {
            font-size: 12px;
            div {
                word-break: break-all;
                white-space: normal;
                .isMe{
                    background-color: rgba(109, 93, 252, 0.2);
                }
            }
            padding: 0px 0px 5px 0px;
            .timeBox {
                background-color: rgba(187, 192, 245, 0.2);
                border-radius: 2px;
                margin-right: 4px;
            }
            .smallText {
                background-color: rgba(241, 218, 222, 0.8);
                border-radius: 2px;
            }
        }
        .more {
            text-align: center;
            background-color: #f5f1f1;
            padding: 10px;
            font-size: 14px;
        }
        .nomore {
            background-color: white;
        }
    }
}
.commentform {
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
    .van-form {
        background-color: white;
        border: 1px solid rgb(192, 190, 190);
        padding: 20px;
        border-radius: 10px;
        .buttonbox {
            display: flex;
            justify-content: center;
            align-items: center;
            .van-button {
                width: 60px;
                margin: 0px 10px;
            }
        }
    }
}
</style>
